import * as signalR from "@microsoft/signalr";
import serveUrl from '../config/serverAddress'; // 导入接口域名列表
import { quitFun } from '@/util/quit';
import initXc from "./xc/signalr";
import store from '../store/index';
// console.clear()
// console.log(serveUrl.st, 'serveUrl.st')
const signalrInit = (token, _this, userid) => {
  let baseUrl_sr = `${serveUrl.st}?userid=${userid}&pt=ent`;
  let that = _this;
  let RelinkNumber = 1;
  let connection;
  function linkSignalr () {
    // 建立连接
    connection = new signalR.HubConnectionBuilder().withUrl(baseUrl_sr, {
      accessTokenFactory: () => token
    }).build();
  }
  linkSignalr();

  function goOnline () {
    // 接受消息
    connection.on("approveCallBack", function (row) {
      console.log('-------------------------------接收到消息------------------------------');
      console.log(row);
      let res = JSON.parse(row);
      // console.log(res, 'res')
      that.$notify({
        title: '',
        dangerouslyUseHTMLString: true,
        duration: 0,
        customClass: 'infoNotify',
        message: res.message,
        type: 'success'
      });
    });
    
    connection.on("noticeCallBack", function (row) {
      console.log('-------------------------------接收到消息------------------------------');
      console.log(row);
      let res = JSON.parse(row);
      // console.log(res, 'res')
      let notify = that.$notify({
        title: '您有一条新的公告,点击查看',
        onClick: function (e) {
          notify.close();
          that.$router.push({
            path: '/AnnouncementManagement',
            query: {
              id: Number(res.id)
            }
          });
          
        },
        dangerouslyUseHTMLString: true,
        duration: 0,
        customClass: 'infoNotify',
        message: res.message,
        // type: 'success'
      });
      notify();
    });

    connection.on("logoutCallBack", function (row) {
      console.log('-------------------------------接收到消息------------------------------退出');
      console.log(row);
      let SerialS = ['F0452', 'f0452', 'F0451', 'f0451'];
      console.log(store.state.common.userInfo.Serial, 'store.state.common.userInfo.Serial;');
      let item = SerialS.find(i=>{
        return i == store.state.common.userInfo.Serial;
      });
      if(process.env.NODE_ENV == 'checkTest' || process.env.NODE_ENV == 'development' || item) {
        return;
      }
      localStorage.setItem('logoutCallBack', true);
      that.$confirm('账号已在别处登录,如不是本人操作，请尽快修改登录密码。', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        closeOnClickModal: false,
        showClose: false,
        type: 'warning'
      }).then(()=>{
        quitFun();
        localStorage.setItem('logoutCallBack', false);
      });
    });
    initXc(connection, that);
  }
  goOnline();

  function signalrInitAgain () {
    if(RelinkNumber >= 2) {
      return false;
    }
    RelinkNumber ++; 
    linkSignalr();
    goOnline();
    start();
    onClose();
    if (process.env.NODE_ENV == 'development' || process.env.NODE_ENV == 'checkTest') { // 链接失败换负载服务器
    }
    if (process.env.NODE_ENV == 'prod') { // 链接失败换负载服务器
    }
  }

  // 开始连接
  connection.start().then(function () {
    RelinkNumber = 1;
  }).catch(function () {
    signalrInitAgain();
  });
  
  // 重新链接方法
  async function start () {
    try {
      await connection.start();
    } catch (err) {
      if(RelinkNumber >= 2) {
        return false;
      }
      setTimeout(() => start(), 5000);
    }
  }

  // 掉线自动重连
  function onClose () {
    connection.onclose(async () => {
      console.log('-----------------------------------------------signalr掉线-----------------------------------------------');
      await signalrInitAgain();
    });
  }
  onClose();
};

export {
  signalrInit,
}; 